/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jsoft.netbeans.dbdesigner.editor;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import org.jsoft.netbeans.dbdesigner.filetype.ERDDataObject;

import org.netbeans.api.db.explorer.ConnectionManager;
import org.netbeans.api.db.explorer.DatabaseConnection;

import org.openide.cookies.SaveCookie;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.Utilities;
import org.openide.windows.CloneableTopComponent;

/**
 * Top component which displays something.
 */
public final class ERDTopComponent extends CloneableTopComponent implements SaveCookie{

    private static ERDTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/jsoft/netbeans/dbdesigner/editor/file-icon.png";

    private static final String PREFERRED_ID = "ERDTopComponent";
    private ERDDataObject object;
    private DBGraphScene graphScene;

    public ERDTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(ERDTopComponent.class, "CTL_ERDTopComponent"));
        setToolTipText(NbBundle.getMessage(ERDTopComponent.class, "HINT_ERDTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
        
    }

    public ERDTopComponent(ERDDataObject erd) {
        initComponents();
        setName(NbBundle.getMessage(ERDTopComponent.class, "CTL_ERDTopComponent"));
        setToolTipText(NbBundle.getMessage(ERDTopComponent.class, "HINT_ERDTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
        this.object = erd;
        graphScene = new DBGraphScene();
        pDesign.add(graphScene.createView());
    }

    private DatabaseConnection askForConnection() {
        DatabaseConnection[] cons = ConnectionManager.getDefault().getConnections();
        ArrayList<String> connections = new ArrayList<String>();
        //String[] connections = new String[cons.length];
        for(int i = 0; i < cons.length; i++)
            connections.add(cons[i].getDisplayName());
        if(connections.size() > 0){
            Object sel = JOptionPane.showInputDialog(null, "", "", JOptionPane.QUESTION_MESSAGE, null, connections.toArray(), connections.get(0));
            DatabaseConnection c = cons[connections.indexOf(sel)];
            if(c.getJDBCConnection() == null){
                ConnectionManager.getDefault().showConnectionDialog(c);
            }
            return c;
        }
        return null;
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        pDesign = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jToggleButton1 = new javax.swing.JToggleButton();

        setLayout(new java.awt.BorderLayout());

        pDesign.setLayout(new java.awt.BorderLayout());
        jScrollPane1.setViewportView(pDesign);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);

        org.openide.awt.Mnemonics.setLocalizedText(jToggleButton1, org.openide.util.NbBundle.getMessage(ERDTopComponent.class, "ERDTopComponent.jToggleButton1.text")); // NOI18N
        jToggleButton1.setFocusable(false);
        jToggleButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jToggleButton1);

        add(jToolBar1, java.awt.BorderLayout.PAGE_START);
    }// </editor-fold>//GEN-END:initComponents

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        DatabaseConnection selected = askForConnection();


        /*
        ConnectionNode node;
        getActivatedNodes()[0].getLookup();//.lookup(ConnectionNode.class);
        
        DatabaseConnection databaseConnection = node.getInfo().getDatabaseConnection().getDatabaseConnection();
        if (databaseConnection.getJDBCConnection() == null) {
            ConnectionManager.getDefault().showConnectionDialog(databaseConnection);
        }
         * */
        //Connection connection = databaseConnection.getJDBCConnection();

    }//GEN-LAST:event_jToggleButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel pDesign;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ERDTopComponent getDefault() {
        if (instance == null) {
            instance = new ERDTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ERDTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ERDTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ERDTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ERDTopComponent) {
            return (ERDTopComponent) win;
        }
        Logger.getLogger(ERDTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_NEVER; // ALWAYS ??
    }
    

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    public void save() throws IOException {
        //this.object.getPrimaryFile().getOutputStream().write("Bonjour le monde seulement pour tester".getBytes());
        this.object.setModified(false);
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return ERDTopComponent.getDefault();
        }
    }
    
}
